﻿/*-------------------------------------
//
//Copyright (C) 2007 开发二组 版权所有。
//
//文件名：CartInfo.cs
//
//
//文件功能描述：显示顾客显示购物的详细信息.
//
//
//创建标识：2007.11.16 王志平
//创建描述：对购物车的商品描述..
//修改标识：2007.11.19 翟丛兴
//修改描述；对购物车的操作的全部要进行修改
//
//------------------------------------*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using JXMSTC.SmartBusiness.BFL.BLLFactory;
using JXMSTC.SmartBusiness.BFL.IBLL;

/// <summary>
/// 购物车页面代码隐藏页
/// </summary>
public partial class Common_Controls_CartInfo : System.Web.UI.UserControl
{
    //顾客ID
    string strCustomerID;
    //保存购物车中商品列表的DataSet
    DataSet dsCartList = new DataSet();
    //创建Cart操作的WebService的代理对象
    localhost.CartService cartServiceObj = new localhost.CartService();

    /// <summary>
    /// 购物车页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //Session["CustomerId"] = null;
            //Session["CustomerID"] = "CUS-00000001";
            //添加商品到购物车
            if (Request.QueryString["ProductID"] != null)
            {
                this.AddProductToCart();
            }
            ////得到购物车列表并显示
            this.GetCartList();
        }
    }

    /// <summary>
    /// 得到购物车商品列表，并绑定到页面
    /// </summary>
    private void GetCartList()
    {
        //判断顾客是匿名顾客还是注册顾客
        if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != String.Empty) && (Session["CustomerID"].ToString() != "CUS-00000000"))
        {
            //如果是注册顾客
            dsCartList = cartServiceObj.GetProductList(Session["CustomerID"].ToString());
            gvResult.DataSource = dsCartList;
            gvResult.DataBind();
            this.CalcullateProduct();
        }
        else
        {
            //如果是匿名顾客
            if (Session["CartList"] != null)
            {
                //如果匿名顾客购物车中不为空，显示
                dsCartList = (DataSet)Session["CartList"];
                gvResult.DataSource = dsCartList;
                gvResult.DataBind();
                this.CalcullateProduct();
            }
            else
            {
                //如果匿名顾客购物车为空
                gvResult.DataSource = null;
                gvResult.DataBind();
            }
        }
    }

    /// <summary>
    /// 计算商品总种数，总件数，和总价格
    /// </summary>
    private void CalcullateProduct()
    {
        if (dsCartList != null)
        {
            //购物车中商品总价格
            decimal totalPrice = 0;
            //购物车中商品总件数
            int totalQuantity = 0; ;
            //购物车中商品的总种数
            int totalKind = dsCartList.Tables[0].Rows.Count;

            //计算商品的总价，总件数和总种数
            DataTable daProductList = dsCartList.Tables[0];
            for (int i = 0; i < totalKind; i++)
            {
                totalQuantity += Convert.ToInt32(daProductList.Rows[i]["Quantity"]);
                totalPrice += Convert.ToDecimal(daProductList.Rows[i]["SalesPrice"]) * Convert.ToInt32(daProductList.Rows[i]["Quantity"]);
            }

            //显示商品的总价，总件数和总种数
            lblTotalKind.Text = totalKind.ToString();
            lblTotalQuantity.Text = totalQuantity.ToString();
            lblTotalPrice.Text = totalPrice.ToString();
        }
        else
        {
            //显示商品的总价，总件数和总种数
            lblTotalKind.Text = "0";
            lblTotalQuantity.Text = "0";
            lblTotalPrice.Text = "0";
        }
    }

    /// <summary>
    /// 添加商品的购物车中
    /// </summary>
    private void AddProductToCart()
    {
        //判断是匿名顾客添加商品，还是注册顾客添加商品

        if ((Request["ProductID"] != null) && ((Session["CustomerID"] == null) || Session["CustomerID"].ToString() == String.Empty) || (Session["CustomerID"].ToString() == "CUS-00000000"))
        {
            //string strProductID = Request["ProductID"].ToString();
            //string strProductID = "SB-1011-3345-0114";
            //如果是匿名用户，添加商品到Session保存的购物车中
            //判断存放购物车商品列表的Session是否存在
            if (Session["CartList"] == null)
            {
                //不存再创建
                CreateCartSesssion();
                Session["CartList"] = dsCartList;
            }

            //得到Session中购物车的商品列表
            //dsCartList = new DataSet();
            dsCartList = (DataSet)Session["CartList"];

            //判断要添加到Session购物车中的商品是否已经存在
            bool blnIsExist = false;
            for (int i = 0; i < dsCartList.Tables["ProductList"].Rows.Count; i++)
            {
                if (dsCartList.Tables["ProductList"].Rows[i]["ProductID"].ToString() == Request["ProductID"].ToString())
                {
                    //如果已存在，数量加1
                    int tempQuantity = Convert.ToInt32(dsCartList.Tables["ProductList"].Rows[i]["Quantity"]);
                    tempQuantity++;
                    dsCartList.Tables["ProductList"].Rows[i]["Quantity"] = tempQuantity.ToString();
                    blnIsExist = true;
                    break;
                }
            }

            if (!blnIsExist)
            {
                //如果Session 购物车中不存在，添加到Session购物车中，并将其数量设为1
                //得到要添加商品的信息
                localhost.ProductService productService = new localhost.ProductService();
                localhost.V_Product v_ProductObj = productService.GetProductInfoByProductID(Request["ProductID"].ToString());

                //添加商品到购物车列表
                DataRow drNewRow = dsCartList.Tables["ProductList"].NewRow();
                drNewRow["ProductID"] = v_ProductObj.ProductID;
                drNewRow["Name"] = v_ProductObj.Name;
                drNewRow["SalesPrice"] = v_ProductObj.SalesPrice.ToString();
                drNewRow["Quantity"] = 1;
                drNewRow["Unit"] = v_ProductObj.Unit;
                dsCartList.Tables["ProductList"].Rows.Add(drNewRow);
            }

            //将购物车列表添加到Session
            Session["CartList"] = dsCartList;
        }
        else if (Request["ProductID"] != null)
        {
            //如果是注册顾客，添加商品的数据库保存的购物车中
            cartServiceObj = new localhost.CartService();
            cartServiceObj.Add(Session["CustomerID"].ToString(), Request["ProductID"].ToString());
        }
    }

    /// <summary>
    /// 创建存放于Session的DataSet的模板
    /// </summary>
    /// <returns></returns>
    public void CreateCartSesssion()
    {
        //创建存储到Sesssion中的保存购物车记录的DataSet
        dsCartList = new DataSet();
        //读取DataSet的框架，因为要符合显示的格式
        dsCartList.ReadXmlSchema(Server.MapPath(".//XML//CartInfo//Cart.xml"));
    }

    /// <summary>
    /// 更改购物车中商品数量
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnChangeQuantity_Click(object sender, EventArgs e)
    {
        //判断是注册顾客还是匿名顾客
        if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != String.Empty) && (Session["CustomerID"].ToString() != "CUS-00000000"))
        {
            //如果是注册顾客
            strCustomerID = Session["CustomerID"].ToString();
            for (int i = 0; i < gvResult.Rows.Count; i++)
            {
                int iNewQuantity = Convert.ToInt32(((TextBox)gvResult.Rows[i].Cells[3].FindControl("txtQuantity")).Text.Trim());
                string strProductID = gvResult.DataKeys[i].Values[0].ToString();
                cartServiceObj = new localhost.CartService();
                cartServiceObj.UpdateProductQuantity(strCustomerID, strProductID, iNewQuantity);
            }
        }
        else
        {
            //如果是匿名顾客
            //取得Session中保存的购物车商品列表
            dsCartList = (DataSet)Session["CartList"];
            for (int i = 0; i < gvResult.Rows.Count; i++)
            {
                int iNewQuantity = Convert.ToInt32(((TextBox)gvResult.Rows[i].Cells[3].FindControl("txtQuantity")).Text);
                dsCartList.Tables[0].Rows[i]["Quantity"] = iNewQuantity;
            }
            Session["CartList"] = dsCartList;
        }
        GetCartList();
    }

    /// <summary>
    /// 删除购物车中的商品
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvResult_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string strProductID = gvResult.DataKeys[e.RowIndex].Value.ToString();
        //判断是注册顾客还是匿名顾客
        if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != String.Empty) && (Session["CustomerID"].ToString() != "CUS-00000000"))
        {
            //如果是注册顾客
            strCustomerID = Session["CustomerID"].ToString();
            cartServiceObj = new localhost.CartService();
            cartServiceObj.DeleteProduct(strCustomerID, strProductID);
        }
        else
        {
            //如果是匿名用户
            dsCartList = (DataSet)Session["CartList"];
            dsCartList.Tables[0].Rows[e.RowIndex].Delete();
        }
        GetCartList();
    }

    /// <summary>
    /// 清空购物车
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnClearCart_Click(object sender, EventArgs e)
    {
        //判断是注册顾客还是匿名顾客
        if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != String.Empty) && (Session["CustomerID"].ToString() != "CUS-00000000"))
        {
            //如果是注册顾客
            strCustomerID = Session["CustomerID"].ToString();
            cartServiceObj = new localhost.CartService();
            cartServiceObj.DeleteAllProduct(strCustomerID);
        }
        else
        {
            //如果是匿名用户
            Session["CartList"] = null;
        }

        //显示商品的总价，总件数和总种数
        lblTotalKind.Text = "0";
        lblTotalQuantity.Text = "0";
        lblTotalPrice.Text = "0";

        GetCartList();
    }

    /// <summary>
    /// 顾客选择结帐，转到填写送货信息页面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnGoBalance_Click(object sender, EventArgs e)
    {
        if (gvResult.Rows.Count > 0)
        {
           Response.Redirect("Balance.aspx");
        }
    }

    /// <summary>
    /// 顾客选择继续购物，跳转到首页
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCoutinueShopping_Click(object sender, EventArgs e)
    {
       Response.Redirect("Default.aspx");
    }
    
    /// <summary>
    /// 数量改变时,总价随着改变
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void txtQuantity_TextChanged(object sender, EventArgs e)
    {
        //判断是注册顾客还是匿名顾客
        if ((Session["CustomerID"] != null) && (Session["CustomerID"].ToString() != String.Empty) && (Session["CustomerID"].ToString() != "CUS-00000000"))
        {
            //如果是注册顾客
            strCustomerID = Session["CustomerID"].ToString();
            for (int i = 0; i < gvResult.Rows.Count; i++)
            {
                int iNewQuantity = Convert.ToInt32(((TextBox)gvResult.Rows[i].Cells[3].FindControl("txtQuantity")).Text);
                string strProductID = gvResult.DataKeys[i].Values[0].ToString();
                cartServiceObj = new localhost.CartService();
                cartServiceObj.UpdateProductQuantity(strCustomerID, strProductID, iNewQuantity);
            }
        }
        else
        {
            //如果是匿名顾客
            //取得Session中保存的购物车商品列表
            dsCartList = (DataSet)Session["CartList"];
            for (int i = 0; i < gvResult.Rows.Count; i++)
            {
                int iNewQuantity = Convert.ToInt32(((TextBox)gvResult.Rows[i].Cells[3].FindControl("txtQuantity")).Text);
                dsCartList.Tables[0].Rows[i]["Quantity"] = iNewQuantity;
            }
            Session["CartList"] = dsCartList;
        }
        GetCartList();
    }

}
